﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Resources;
using System.Xml;
using System.Xml.Linq;
using Com.CodePlex.SPPower.Model;
using System.Xml.XPath;

namespace Com.CodePlex.SPPower.Data {

	public class HistoryRepository {

		public IList<ViewModel.HistoryViewModel> Load() {
			List<ViewModel.HistoryViewModel> result = new List<ViewModel.HistoryViewModel>();
			if (File.Exists(Properties.Settings.Default.File_History)) {
				XElement root = XDocument.Load(Properties.Settings.Default.File_History).Root;
                result.AddRange(
                    root
                    .Elements("item")
                    .Select(i => new ViewModel.HistoryViewModel(i.Attribute("cmd").Value, DateTime.Parse(i.Attribute("timestamp").Value)) {
                        Log = i.Element("log").Value,
                        Parameters = i
                            .Element("parameters")
                            .Elements("parameter")
                            .Select(j => new Service.CmdParameter() {
                                Name = j.Attribute("name").Value,
                                Value = j.Attribute("value").Value//,
                                //Type = j.Attribute("type").Value
                            }).ToList()
                    })
                );
			}
			return result;
		}

		public void Append(ViewModel.HistoryViewModel item) {
			XElement xml = new XElement("history");
			if (File.Exists(Properties.Settings.Default.File_History)) {
				xml = XDocument.Load(Properties.Settings.Default.File_History).Root;
			}
			xml.Add(new XElement("item", 
				new XAttribute("cmd", item.Cmd), 
				new XAttribute("timestamp", item.Timestamp), 
                new XElement("parameters", 
					from i in item.Parameters
                    where i.Value != null
                    select new XElement("parameter",
						new XAttribute("name", i.Name),
						new XAttribute("value", i.Value),
                        new XAttribute("type", i.Type)
					)
                ),
				new XElement("log", item.Log)));
			xml.Save(Properties.Settings.Default.File_History);
		}
	}
}